package com.newfiber.business.controller.websocket;

import static cn.hutool.core.date.DatePattern.PURE_DATETIME_PATTERN;

import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson2.JSONObject;
import com.newfiber.business.domain.request.patrolPath.PatrolPathSaveRequest;
import com.newfiber.business.enums.EPatrolRedisKey;
import com.newfiber.common.redis.service.RedisService;
import java.util.Date;
import javax.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

/**
 * @author : X.K
 * @since : 2023/3/6 下午2:15
 */
@Slf4j
public class PatrolPathWebReportSocket extends TextWebSocketHandler{

	@Resource
	private RedisService redisService;

	@Resource
	private PatrolPathWebNotifySocket notifySocket;

	@Override
	public void afterConnectionEstablished(WebSocketSession session) throws Exception {
		log.info("WebSocket连接启动成功");
	}

	@Override
	protected void handleTextMessage(WebSocketSession session, TextMessage message){
		Date now = new Date();

		// 保存巡查轨迹
		String payload = message.getPayload();
		PatrolPathSaveRequest request = JSONObject.parseObject(payload, PatrolPathSaveRequest.class);

		if(null == request.getRefId()){
			return;
		}

		// 巡查路径通知websocket
		request.setPatrolDatetime(now);
		request.setRefId(request.getRefId().toString());
		notifySocket.notifyPatrolPath(request);

		// 路径放到缓存
		String redisKey = String.format("%s:%s", request.getRefId(), DateUtil.format(now, PURE_DATETIME_PATTERN));
		redisService.setCacheObject(EPatrolRedisKey.PatrolPath, redisKey, JSONObject.toJSONString(request));

		log.info(String.format("上报轨迹：refId:%s, 时间:%s, 坐标:%s", request.getRefId(), DateUtil.format(now, PURE_DATETIME_PATTERN), request.getLonLat()));

		// 如果上传了巡查轨迹，那么今天就在线
		if(!redisService.hasKey(EPatrolRedisKey.TodayPatrolTask, String.valueOf(request.getRefId()))){
			long timeout = DateUtil.between(now, DateUtil.endOfDay(now), DateUnit.SECOND);
			redisService.setCacheObject(EPatrolRedisKey.TodayPatrolTask, String.valueOf(request.getRefId()),
				String.valueOf(request.getRefId()), timeout);
		}

	}

	@Override
	public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
		log.error("WebSocket错误：" + exception.getMessage());
	}

	@Override
	public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
		log.debug("WebSocket连接已关闭");
	}
}
